package com.bjzsly.star3.xyh.utils;


import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;

import com.bjzsly.star3.xyh.base.AppClient;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by ly on 2017/5/9.
 * some issues which may be used for many times
 */

public class SimplePostHelper<T> {

    private Handler handler = new Handler(Looper.getMainLooper());

//    public static void uploadImage(HashMap<String, Object> map, final UploadCallBack uploadCallBack) {
//        MultipartBody.Builder builder = new MultipartBody.Builder();
//        builder.setType(MultipartBody.FORM);
//
//        Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
//        while (it.hasNext()) {
//            Map.Entry<String, Object> entry = it.next();
//            String key = entry.getKey();
//            Object obj = entry.getValue();
//            addToMultiBody(builder, key, obj);
//        }
//
//        MultipartBody body = builder.build();
//        String token = LoginManager.getInstance().getUnCheckToken();
//        if (token == null) return;
//        AppClient.getApiService().postImg(token, body)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Subscriber<ResultResponse<String>>() {
//                    @Override
//                    public void onCompleted() {
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        try {
//                            if (uploadCallBack != null) uploadCallBack.onUpError(e.toString());
//                        } catch (Exception e1) {
//
//                        }
//                    }
//
//                    @Override
//                    public void onNext(ResultResponse<String> ResultResponse) {
//                        try {
//                            if (uploadCallBack != null) {
//                                if (ResultResponse.code.equals("0")) {
//                                    uploadCallBack.onUpSuccess(ResultResponse.data);
//                                } else {
//                                    uploadCallBack.onUpError(ResultResponse.msg);
//                                }
//                            }
//
//                        } catch (Exception e) {
//                            uploadCallBack.onUpError("上传失败");
//                        }
//                    }
//                });
//    }

    private static void addToMultiBody(MultipartBody.Builder builder, String key, Object obj) {
        if (obj instanceof File) {
            RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpg"), (File) obj);
            builder.addFormDataPart(key, getPhotoFileName(), fileBody);
        } else if (obj instanceof String) {
            builder.addFormDataPart(key, (String) obj);
        }
    }

    private static String getPhotoFileName() {
        Date curDate = new Date(System.currentTimeMillis());
        SimpleDateFormat formatter = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
        return formatter.format(curDate) + ".jpg";
    }




    public void normalPost(Observable observable, final SimpleCallBack callBack) {
        if (observable != null) {
            observable.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<T>() {

                        @Override
                        public void onCompleted() {
                        }

                        @Override
                        public void onError(Throwable e) {
                            if (callBack != null) callBack.onError(e.toString());
                        }

                        @Override
                        public void onNext(T result) {
                            try {
                                if (callBack != null) {
                                    callBack.onSuccess(result);
                                }
                            } catch (Exception e) {
                                callBack.onError(e.toString());
                            }
                        }
                    });
        } else {
            if (callBack != null) callBack.onError("Error");
        }
    }


    public void downloadImage(final Context ctx, String url, final String filePath, final DownloadCallBack downloadCallBack) {
        AppClient.getApiService().downloadImage(url)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<ResponseBody>() {
                    @Override
                    public void call(ResponseBody responseBody) {
                        saveImageToPath(ctx, responseBody, filePath);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(final Throwable throwable) {
                        if (handler != null) {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    if (downloadCallBack != null)
                                        downloadCallBack.downloadError(throwable.toString());
                                }
                            });
                        }
                    }
                });
    }

    public static void downloadImage(final Context ctx, final DownloadCallBack downLoadCallBack, List<String> urlList) {
        try {
            String urls[] = new String[urlList.size()];
            for (int i = 0; i < urlList.size(); i++) {
                urls[i] = urlList.get(i);
            }
            downloadImage(ctx, downLoadCallBack, urls);
        } catch (Exception e) {
        }

    }

    public static void downloadImage(final Context ctx, final DownloadCallBack downLoadCallBack, String... urls) {
        if (urls == null || urls.length == 0) return;
        Observable.from(urls).subscribeOn(Schedulers.io()).observeOn(Schedulers.io())
                .flatMap(new Func1<String, Observable<ResponseBody>>() {
                    @Override
                    public Observable<ResponseBody> call(String s) {
                        return AppClient.getApiService().downloadImage(s);
                    }
                })
                .map(new Func1<ResponseBody, String>() {

                    @Override
                    public String call(ResponseBody responseBody) {
                        try {
                            String filePath = new File(ConstanceValue.IMG_TEMP_DIR, System.currentTimeMillis() + ".jpg").getAbsolutePath();
                            if (saveImageToPath(ctx, responseBody, filePath)) {
                                return filePath;
                            }
                        } catch (Exception e) {
                        }
                        return null;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String filePath) {
                        if (downLoadCallBack != null)
                            downLoadCallBack.downloadComplete(filePath);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(final Throwable throwable) {

                        if (downLoadCallBack != null)
                            downLoadCallBack.downloadError(throwable.toString());
                    }
                });

    }


    public static boolean saveImageToPath(Context ctx, ResponseBody body, final String filePath) {
        try {
            InputStream is = body.byteStream();
            File file = new File(filePath);
            if (!file.exists()) file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            fos.flush();
            fos.close();
            bis.close();
            is.close();


            ctx.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + filePath)));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public interface UploadCallBack {

        void onUpSuccess(String url);

        void onUpError(String error);

    }

    public interface DownloadCallBack {
        void downloadComplete(String paths);

        void downloadError(String url);
    }


    public interface SimpleCallBack<T> {
        void onSuccess(T data);

        void onError(String msg);

        void onFail(String msg);

    }
}
